﻿$(function () {
    //初始化选择框插件
    $('select').select2();

	//初始化提示工具
    $('[data-toggle="tooltip"]').tooltip({trigger:'hover'});

    //初始化表格横向滚动条
    $('.table-scrollx').niceScroll({
        cursorcolor:"#232f3f",
        cursorwidth:"12px",
        background:"#ddd"
    });

    //头部二级菜单显示&隐藏
    $('#menu > .menu-item').hover(
        function(){
            $(this).find('.menu-layer').show();
        },
        function(){
            $(this).find('.menu-layer').hide();
        }
    );

    //收起展开左边栏
    $(".nav-slidedown").on("click",function(){
        var w = $('#left').outerWidth(),
            l = $('.nav-slideup').outerWidth();
        $('#left').css('left',-w);
        $('#main').css('padding-left',l-10);
        $('.crumbs').css('padding-left',l);
        $('.nav-slideup').show();
        fixedTableHeader();//表头纵向固定
    });
    $(".nav-slideup").on('click',function(){
        var w = $('#left').outerWidth();
        $('#left').css('left',0);
        $('#main').css('padding-left',w);
        $('.crumbs').css('padding-left',10);
        $(this).hide();
        fixedTableHeader();//表头纵向固定
    });

    //左边栏二级导航显示&隐藏
    $('#nav > li').mouseenter(function(){
        var i = $(this).index();
        $(this).addClass('current');
        $('#sub-nav-box').show().children('.sub-nav-block').eq(i).show();
    });
    $('#nav > li').mouseleave(function(){
        $(this).removeClass('current');
        $('#sub-nav-box').hide().children('.sub-nav-block').hide();
    });
    $('#sub-nav-box > .sub-nav-block').mouseenter(function(){
        var i = $(this).index();
        $('#nav').children("li").eq(i).addClass('current');
        $(this).show();
        $('#sub-nav-box').show();
    });
    $('#sub-nav-box > .sub-nav-block').mouseleave(function(){
        $('#nav').children("li").removeClass('current');
        $('#sub-nav-box').hide().children('.sub-nav-block').hide();
    });

    //展开收起更多筛选
    $('.filter').find('.more').on('click',function(){
        var parents = $(this).parents('.filter');
        if($(this).hasClass('on')){
            parents.find('.filter-item.hide').hide();
            $(this).removeClass('on').html('更多筛选<i class="fa fa-angle-down"></i>');
        }else{
            parents.find('.filter-item.hide').show();
            $(this).addClass('on').html('收起筛选<i class="fa fa-angle-up"></i>');
        }
    });

    //选中筛选默认展开更多筛选
    $(".filter").find(".filter-item:gt(3)").each(function(){
        if(!$(this).find(".filter-order > li:first").hasClass("current")){
            var parents = $(this).parents('.filter');
            parents.find('.filter-item.hide').show();
            parents.find('.more').addClass('on').html('收起筛选<i class="fa fa-angle-up"></i>');
            return false;
        }
    });
    //注意事项弹出层
	$(".toolbar-annotation").hover(function(){
		if($(".annotation-item").is(":not(:animated)")){
			$(".annotation-item").fadeIn(300);
		}
	},function(){
		if($(".annotation-item").is(":not(:animated)")){
			$(".annotation-item").fadeOut(300);
		}
	});
    //表头选择框提示
    $('.table-header').find('select').each(function(){
        if(!$(this).find('option:first').prop('selected')){
            $(this).next('.select2').addClass('color-active');
        }
    })
    //格式化日期
    var formatDate = function (date) {  
        var y = date.getFullYear();  
        var m = date.getMonth() + 1;  
        m = m < 10 ? '0' + m : m;  
        var d = date.getDate();  
        d = d < 10 ? ('0' + d) : d;  
        return y + '-' + m + '-' + d;  
    };  
    //表头纵向固定
    $(window).scroll(function(){
        fixedTableHeader();
    });
    $(window).resize(function(){
        fixedTableHeader();
    });
    fixedTableHeader();
    function fixedTableHeader(){
        if($('.table-scrollx').find('.fixed-table-header').length>0){
            var table_scrollx = $('.table-scrollx'),
                header = $('.fixed-table-header'),
                scroll_top = $(window).scrollTop(),
                table_top = header.parents('table').offset().top,
                ratio = $('#header').outerHeight();
            //显示隐藏表头
            if(table_top-scroll_top<=ratio){
                var width = header.parents('table').outerWidth(),
                    top = scroll_top-table_top+ratio;
                if(table_scrollx.find('.table-header-clone').length==0){
                    var clone = header.find('td').clone().removeAttr('style width');
                    clone.find('.select2,.tooltip').remove();
                    clone.find('select').removeClass('select2-hidden-accessible');
                    clone.find('[data-toggle="tooltip"]').tooltip({trigger:'hover'});
                    table_scrollx.append('<div class="table-header-clone"></div>');
                    table_scrollx.find('.table-header-clone').html(clone);
                    //加载选择框插件
                    table_scrollx.find('.table-header-clone select').each(function(){
                        $(this).select2();
                        if(!$(this).find('option:first').prop('selected')){
                            $(this).next('.select2').addClass('color-active');
                        }
                    });
                }
                table_scrollx.find('.table-header-clone').css({'top':top,'width':width});
                //遍历单元格位置
                header.find('td').each(function(i){
                    var left = 0;
                    if(i>0){
                        $(this).prevAll('td').each(function(){
                            left+=$(this).outerWidth();
                        });
                    }
                    table_scrollx.find('.table-header-clone td').eq(i).css('left',left);
                });
            }else{
                table_scrollx.find('.table-header-clone').remove();
            }
        }
    }

    //使用帮助
    $(".using-help-btn").on('click',function(){
        var w = $('#using-help').outerWidth();
        $('#using-help').show();
        $('#main').css('padding-right',w);
        fixedTableHeader();//表头纵向固定
    });
    $('#using-help').find('.help-close').on('click',function(){
        $('#using-help').hide();
        $('#main').css('padding-right',0);
        fixedTableHeader();//表头纵向固定
    });

    //页面返回
    $('.goback').on('click',function(){
        history.back();
    });

    //阻止事件冒泡
    $(document).on('click','.stopevent',function(event){
        event.stopPropagation();
    });    
});

//提交验证错误提示框
function defeated_alert(msg){
    $("body").append("<div class='modal-backdrop fade'></div><div class='success-defeated hide'>"+msg+"</div>");
    var defeated = $(".success-defeated"),
        t = -defeated.outerHeight()/2,
        l = -defeated.outerWidth()/2;
    $(".modal-backdrop").addClass("in");
    defeated.css({"margin-top":t,"margin-left":l}).slideDown();
    $(".modal-backdrop").on("click",function(){
        $(".modal-backdrop,.success-defeated").remove();
    });
}

//ajax传递返回提示框
function success_pop(status,msg,seconds,url){
    if(!$(".modal-backdrop").hasClass("in")){
        $("body").append("<div class='modal-backdrop fade'></div>");
        if($(".modal-backdrop").outerWidth()){
            $(".modal-backdrop").addClass("in");
        }
    }else{
        $(".modal-backdrop").off("click");
    }

    var $html="",$status,$msg,$seconds,$timeset;

    if(status){
        $status = "succeed";
    }else{
        $status = "defeated";
    }
    if(msg){
        $msg = msg;
    }else{
        if(status){
            $msg = "操作成功";
        }else{
            $msg = "操作失败";
        }
    }
    if(seconds){
        $seconds = seconds;
    }else{
        $seconds = 1;
    }
    $html += "<div class='success-dialog hide "+$status+"'>";
    $html += "<div class='title'>"+$msg+"</div>";
    $html += "<span class='seconds-go'>"+$seconds+"</span>秒后跳转";
    if($seconds>=3){
        $html += "<i class='fa fa-times box-close'></i>";
    }
    $html += "</div>";
    $("body").append($html);
    $(".success-dialog").slideDown();
    $(".success-dialog .box-close").on("click",function(){
        if(url){
            location.href = url;
        }else{
            location.replace(location.href);
        }
    });

    $timeset = setInterval(function(){
        $(".seconds-go").text($seconds--);
        if($seconds==0){
            clearInterval($timeset);
            if(url){
                // window.onload=function(){
                //   location.hash='#4';
                // }
                location.href = url;
            }else{
                location.replace(location.href);
            }
        }
    },1000);
}

//JS浮点数加法
function accAdd(arg1, arg2) {
    var r1, r2, m, c;
    try{
        r1 = arg1.toString().split(".")[1].length;
    }
    catch(e){
        r1 = 0;
    }
    try{
        r2 = arg2.toString().split(".")[1].length;
    }
    catch(e){
        r2 = 0;
    }
    c = Math.abs(r1 - r2);
    m = Math.pow(10, Math.max(r1, r2));
    if(c > 0){
        var cm = Math.pow(10, c);
        if(r1 > r2){
            arg1 = Number(arg1.toString().replace(".", ""));
            arg2 = Number(arg2.toString().replace(".", "")) * cm;
        }else{
            arg1 = Number(arg1.toString().replace(".", "")) * cm;
            arg2 = Number(arg2.toString().replace(".", ""));
        }
    }else{
        arg1 = Number(arg1.toString().replace(".", ""));
        arg2 = Number(arg2.toString().replace(".", ""));
    }
    return (arg1 + arg2) / m;
}

//JS浮点数减法
function accSub(arg1, arg2) {
    var r1, r2, m, n;
    try{
        r1 = arg1.toString().split(".")[1].length;
    }
    catch(e){
        r1 = 0;
    }
    try{
        r2 = arg2.toString().split(".")[1].length;
    }
    catch(e){
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

//JS浮点数乘法
function accMul(arg1, arg2) {
    var m = 0, s1 = arg1.toString(), s2 = arg2.toString();
    try{
        m += s1.split(".")[1].length;
    }
    catch(e){}
    try{
        m += s2.split(".")[1].length;
    }
    catch(e){}
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

//JS浮点数除法
function accDiv(arg1, arg2) {
    var t1 = 0, t2 = 0, r1, r2;
    try{
        t1 = arg1.toString().split(".")[1].length;
    }
    catch(e){}
    try{
        t2 = arg2.toString().split(".")[1].length;
    }
    catch(e){}
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""));
        r2 = Number(arg2.toString().replace(".", ""));
        return (r1 / r2) * pow(10, t2 - t1);
    }
}

//自定义插件
(function($){
    $.fn.extend({
        //搜索
        keywordSearch:function(url){
            var $this = this,
                keyword = $this.parents('.input-group').find('#keyword');
            $this.on('click',function(){
                var val = keyword.val();
                window.location.href = url.replace(/\$keyword/,val);
            });
            document.onkeydown = function(ev){
                var oEvent = ev||event;
                if(oEvent.keyCode==13 && keyword.is(":focus")){
                    $this.click();
                }
            }
        },
        //ajax传递返回提示框
        ajaxModal:function(options){
        	this.on('click',function(){
                var $this = $(this),
                	defaluts = {title_text:"",body_text:""},
                    opts = $.extend({},defaluts,options),
                    html = "";
                html+="<div id='ajaxModal' class='modal fade'>";
                html+="<div class='modal-dialog'>";
                html+="<div class='modal-content'>";
                html+="<div class='modal-header'>";
                html+="<h4>"+opts.title_text+"</h4>";
                html+="<i class='fa fa-times' aria-hidden='true' data-dismiss='modal'></i>";
                html+="</div>";
                html+="<div class='modal-body'>"+opts.body_text+"</div>";
                html+="<div class='modal-footer'>";
                html+="<button type='button' class='btn btn-confirm'>确认</button>";
                html+="<button type='button' class='btn btn-default' data-dismiss='modal'>取消</button>";
                html+="</div>";
                html+="</div>";
                html+="</div>";
                html+="</div>";
                $("body").append(html);
                var ajaxmodal = $('#ajaxModal');
                ajaxmodal.modal();
                //确认
                ajaxmodal.find('.btn-confirm').off().on('click',function(){
                    //遍历数据赋值
                    for(var i in opts.data){
                        opts.data[i] = $this.attr(opts.data[i]);
                    }
                    ajaxmodal.hide();
                    $.ajax({
                        type:"POST",
                        async:false,
                        dataType:"json",
                        data:opts.data,
                        url:opts.url,
                        success:function(data){
                            success_pop(data['status'],data['msg']);
                        }
                    });
                });
                //取消
                ajaxmodal.on('hidden.bs.modal',function(){
                    $(this).remove();
                });
            });
        }
    });
})(jQuery);